﻿using System;
using cludg.Domain.Users;
using cludg.Repository.Security;
using cludg.Repository.Transactions;
using cludg.Services.Images;
using cludg.Infrastructure.Core.Attributes;

namespace cludg.Services.Users
{
	public class UserService : IUserService
	{
		[Dependency]
		public IImageService ImageService { get; set; }

		[Dependency]
		public ISecurityRepository SecurityRepository { get; set; }

		[Dependency]
		public ITransactionFactory TransactionFactory { get; set; }

		public void ChangeUserAvatar(string userId, System.IO.Stream stream)
		{
			User user = SecurityRepository.GetUserById(userId);
			using (var tran = TransactionFactory.BeginTransaction())
			{
				if (stream == null)
				{
					user.Avatar = string.Empty;
					user.SmallAvatar = string.Empty;
				}
				else
				{
					string[] ids = ImageService.Add(stream, new[] {ImageSize.Real, ImageSize.SmallAvatar, ImageSize.Avatar});
					user.SmallAvatar = ids[1];
					user.Avatar = ids[2];
				}
				SecurityRepository.SaveUser(user);
				tran.Commit();
			}
		}

		public void UpdateUser(User user)
		{
			using (var tran = TransactionFactory.BeginTransaction())
			{
				SecurityRepository.SaveUser(user);
				tran.Commit();
			}
		}
	}
}
